package com.foreveross.chameleon_template;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.RelativeLayout;
import com.foreveross.bsl.util.AssetTool;
import com.foreveross.bsl.util.Preferences;
import com.foreveross.chameleon.R;
import com.foreveross.chameleonsdk.CModule;
import com.foreveross.chameleonsdk.config.URL;
import com.foreveross.utils.crypt.AesTool;
import com.foreveross.utils.crypt.CryptUtils;
import com.foss.AppLog;
import com.foss.DeviceInfoUtil;
import com.foss.GeneralUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;

public class MainActivity_bak_20140901 extends Activity {
    private TemplateApplication temphetApplication;
    private RelativeLayout layout;
    private Context mCtx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (DeviceInfoUtil.isPad()) {
            setContentView(R.layout.pad_splash_screen);
        } else {
            setContentView(R.layout.phone_splash_screen);
        }
        mCtx = this;
        temphetApplication = TemplateApplication.class.cast(MainActivity_bak_20140901.this.getApplication());
        layout = (RelativeLayout) findViewById(R.id.welcome_loadinglayout);


        copyIfNecessory();
    }

    /**
     * if first install or folder is not exist ,do full copy
     * else check version,just copy new version files
     */
    private void copyIfNecessory() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                AppLog.i("------do some copy at app start -------");
                boolean isFirst = Preferences.getFirsttime();
                File wwwFolder = new File(URL.APP_FOLDER_IN_SD + "/www");
                boolean isCopyAll = isFirst || !wwwFolder.exists();
                if (isCopyAll) {
                    AppLog.i("copyAll,isFirst=" + isFirst + "wwwFolder=" + wwwFolder.getAbsolutePath());
                    copyAll();
                } else {
                    int preSavedVer = Preferences.getVersionCode();
                    int currVer = GeneralUtils.getVersionCode();
                    AppLog.i("preSavedVer=" + preSavedVer + ",currVer=" + currVer);
                    boolean isUpdateCopy = currVer > preSavedVer;
                    if (isUpdateCopy) {
                        AppLog.i("copyByVersion");
                        copyByVersion();
                    } else {
                        AppLog.i("do not neet copy anything");
                    }
                }

                AppLog.i("------copy task done-------");
                Preferences.saveFirsttime(false);
                Preferences.saveVersionCode(GeneralUtils.getVersionCode());

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        layout.setVisibility(View.INVISIBLE);
                        init();
                    }
                });
            }
        }).start();

    }

    // 完全拷贝
    private void copyAll() {
        AssetTool assetTool = new AssetTool();
        assetTool.copyAsset(mCtx, "www", URL.APP_FOLDER_IN_SD);
    }

    // 部分拷贝, plugins文件夹 cordova.js cordova_plugins.js
    // www/xxx/文件夹下,如果含有 CubeModule.json,并且build字段较小，则更新
    private void copyByVersion() {
        final String CUBE_MODUEL_JSON = "CubeModule.json";

        //
        AssetTool assetTool = new AssetTool();
        assetTool.copyAsset(mCtx, "www/plugins", URL.APP_FOLDER_IN_SD);
        assetTool.copyAsset(mCtx, "www/cordova.js", URL.APP_FOLDER_IN_SD);
        assetTool.copyAsset(mCtx, "www/cordova_plugins.js", URL.APP_FOLDER_IN_SD);

        //
        AssetManager assetManager = mCtx.getAssets();
        String wwwFolder[] = null;
        try {
            wwwFolder = assetManager.list("www");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (wwwFolder == null || wwwFolder.length == 0) {
            return;
        }

        for (String aFileInWww : wwwFolder) {
            String[] child = null;
            try {
                child = assetManager.list("www/" + aFileInWww);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (child == null || child.length == 0) {
                continue; // not a folder or empty folder
            }
            if (!Arrays.asList(child).contains(CUBE_MODUEL_JSON)) {
                continue; // no CubeModule.json
            }

            //AppLog.i("has CubeModule.json : www/" + aFileInWww);
            final String folder = "www/" + aFileInWww;
            final String jsonFile = folder + "/" + CUBE_MODUEL_JSON;
            try {
                // read CUBE_MODUEL_JSON => String =>JSON
                File f = new File(URL.APP_FOLDER_IN_SD + "/" + jsonFile);
                InputStream inSd = new FileInputStream(f);
                int savedBuild = getBuild(inSd);
                inSd.close();

                InputStream in = assetManager.open(jsonFile);
                int currBuild = getBuild(in);
                in.close();

                AppLog.i("copy file : www/" + aFileInWww);
                //AppLog.i("currBuild=" + currBuild + ",savedBuild=" + savedBuild);
                //
                if (currBuild > savedBuild) {
                    assetTool.copyAsset(mCtx, folder, URL.APP_FOLDER_IN_SD);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private int getBuild(InputStream in) throws IOException, JSONException {
        final String BUILD = "build";
        //
        InputStream targetIn = null;
        targetIn= AesTool.getInstance().decryptStream(in);
        if (targetIn == null) {
            targetIn = in;
        }
        String str = CryptUtils.stream2String(targetIn, "UTF-8");
        //AppLog.i("getBuild jsonstr = " + str);
        JSONObject json = new JSONObject(str);
        return json.getInt(BUILD);
    }


    private void goToFirstModule() {
        HashMap<String, CModule> modules = temphetApplication.getCApplication().getModules();
        for (CModule module : modules.values()) {
            String activity = module.getActivity();
            if (module.isFirstStart()) {
                Intent intent = new Intent();
                intent.setClassName(this, activity);
                this.startActivity(intent);
                finish();
            }
        }
    }


    /*
     * 初始化方法实现
     */
    private void init() {
        // 启动加载页面方式：一
        final long currentStart = System.currentTimeMillis();
        new Thread(new Runnable() {

            public void run() {
                // 休眠标识
                boolean flag = false;
                while (!flag) {
                    // 如果休眠时间小于两秒，继续休眠
                    if (System.currentTimeMillis() - currentStart > 1000) {
                        flag = true;
                        goToFirstModule();
                    }
                }
            }
        }).start();
    }
}
